package com.iwechat.adapter.mina.entity;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;

public class ConnectResp extends PDUHeader {
    public static final int command = PDU.COMMAND_CONNECT_RESP;
    public static final int pkgLen  = PDU.HEAD_LEN + 32 + 4;

    /** 客户端ID : fixed 32 bytes,right padding space */
    private String          clientID;

    /** 错误码 */
    private int             errorCode;

    /**
     * 根据Connect构造ConnectResp for send
     *
     *
     * @param Connect
     * @param errorCode
     * @throws Exception
     */
    public ConnectResp(Connect connect, int errorCode) throws Exception {
        this.sequence = connect.getSequence();
        this.timestamp = System.currentTimeMillis();
        this.clientID = connect.getClientID();
        this.errorCode = errorCode;
    }

    /**
     * 根据header构造ConnectResp for receive
     *
     *
     * @param header
     * @param encoder
     * @throws Exception
     */
    public ConnectResp(PDUHeader header, IoBuffer in, Charset charset) throws Exception {
        this.sequence = header.getSequence();
        this.timestamp = header.getTimestamp();

        byte[] data = new byte[32];
        in.get(data);
        this.clientID = new String(data, charset);

        this.errorCode = in.getInt();
    }

    public String getClientID() {
        return clientID;
    }

    public int getErrorCode() {
        return errorCode;
    }

    @Override
    public IoBuffer toIoBuffer(Charset charset) throws CharacterCodingException {
        IoBuffer buffer = IoBuffer.allocate(pkgLen);
        buffer.putInt(pkgLen);
        buffer.putInt(command);
        buffer.putInt(sequence);
        buffer.putLong(timestamp);

        buffer.put(clientID.getBytes(charset));
        buffer.putInt(errorCode);

        buffer.flip();
        return buffer;
    }

    @Override
    public String toString() {
        return "ConnectResp [pkgLen=" + pkgLen + ", command=" + command + ", sequence=" + sequence + ", timestamp=" + timestamp + ", clientID="
                + clientID.trim() + ", errorCode=" + errorCode + "]";
    }

    public void setClientID(String clientID) {
        this.clientID = clientID;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}
